package cn.virens.web.components.weixin.handler.base;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.virens.web.components.weixin.session.VirWxSessionManager;
import cn.virens.web.components.weixin.session.support.SupportSessionManager;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

public abstract class AbstractWxMpMessageHandler implements WxMpMessageHandler {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
		AbstractWxMpMessageUser wxMpMessageUser = new AbstractWxMpMessageUser(wxMpXmlMessage.getFromUser());
		wxMpMessageUser.setWxMpXmlMessage(wxMpXmlMessage);
		wxMpMessageUser.setWxMpService(wxMpService);
		wxMpMessageUser.setAttributes(context);

		try {
			if (sessionManager instanceof VirWxSessionManager) {
				wxMpMessageUser.setSessionManager((VirWxSessionManager) sessionManager);
			}

			if (sessionManager instanceof SupportSessionManager) {
				wxMpMessageUser.setSessionManager(((SupportSessionManager) sessionManager).manager());
			}

			return handle(wxMpXmlMessage, wxMpMessageUser);
		} finally {
			wxMpMessageUser.saveSession();
		}
	}

	protected WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, WxMpMessageUser wxMpMessageUser) {
		return null;
	}
}
